var sys = require('sys'),
    redis = require('./redisclient');

exports.start= function(callback) {
  var client = new redis.Client();

  client.addListener('connect', function() {
    callback(client);
  });

  client.connect();
};

//Set data
exports.set = function(conn, config){
  return function(e) {
    var that = this;
    var data = (config.attrib) ? e[config.attrib] : e;
    conn.set(this.id+':'+config.key, JSON.stringify(data), function(err, value) {
      if(err) {
        puts("Redis error during dataSet:"+err+","+value);
      } else {
        if(config.callback && typeof(config.callback) === 'function') {
          config.callback.call(that, e);
        }
      }
    });
  };
};

//Add data to a sorted set
exports.sorted_add = function(args) {

  return function(data, callback) {
    var that = this;
    var _data = (args.attrib) ? data[args.attrib] : data;
    var score = (args.score) ? data[args.score] : 0;

    args.conn.zadd(this.id+':'+config.key, score, JSON.stringify(_data), function(err, value) {
      if(err) {
        puts("Redis error during eventDataSetAdd:"+err+","+value);
      } else {
        callback(data);
      }
    });
  };
};

//Push data into redis
exports.push = function(args) {

  return function(data, callback) {
    args.conn.lpush(this.id+':'+args.key, JSON.stringify(data), function(err, value) {
      if(err) {
        puts("Redis error during push:"+err+","+value);
        callback();
      } else {
        callback(data);
      }
    });
  };
};

/**
 *
 */
exports.trim = function(args) {

  return function(data, callback) {
    args.conn.ltrim(this.id+':'+args.key, 0, args.max-1, function(err, value) {
      if(err) {
        puts("Redis error during push:"+err+","+value);
        callback();
      } else {
        callback(data);
      }
    });
  };
};

